package com.framework.loippi.utils;

import java.awt.Button;
import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class GSONUtils {
	private static final String fullDatePattern = "yyyy-MM-dd HH:mm:ss";

    private final static ThreadLocal<Gson> THREAD_LOCAL = new ThreadLocal<Gson>()
        {

            @Override
            protected Gson initialValue() {
                GsonBuilder builder = new GsonBuilder();
                builder.setDateFormat(fullDatePattern);
                return builder.create();
            }

        };

    public static String toJson(Object obj) {
        return THREAD_LOCAL.get().toJson(obj);
    }

    public static <T> T fromJson(String jsonStr, Class<T> classOfT) throws JsonSyntaxException {
        return THREAD_LOCAL.get().fromJson(jsonStr, classOfT);
    }

    public static <T> T fromJson(String jsonStr, Type typeOfT) throws JsonSyntaxException {
        return THREAD_LOCAL.get().fromJson(jsonStr, typeOfT);
    }
    
	@SuppressWarnings("unchecked")
	public static Object serialize(String jsonString, Class object){
		Gson gson = new Gson();
		return gson.fromJson(jsonString, object);
	}
	
	@SuppressWarnings("unchecked")
	public static String deserialize(String jsonString, Class beanclass){
		GsonBuilder gsonb = new GsonBuilder();
		gsonb.setDateFormat("yyyy-MM-dd HH:mm:ss");
		Gson gson = gsonb.create();
		return (String) gson.fromJson(jsonString, beanclass);
	}
	public static String valueToString(Object obj) {
		Gson gson = new Gson();
		return gson.toJson(obj);  
	}
	
	public static void main(String[] args) {
		Button button = new Button();
		button.setName("ss");
		System.out.println(GSONUtils.valueToString(button));
	}
	
}
